/*
 * @(#)MtmDocumentVersion.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.MtmDocumentVersion;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.web.AbstractSearchForm;

/**
  MtmDocumentVersionDAObject.java

  This class is the data access bean for table "MTM_DOCUMENT_VERSION".

  @author      Zoe Shum
  @company     DCIVision Limited
  @creation date   31/07/2003
  @version     $Revision: 1.15 $
*/

public class MtmDocumentVersionDAObject extends AbstractDAObject {

  public static final String REVISION = "$Revision: 1.15 $";

  public static final String TABLE_NAME = "MTM_DOCUMENT_VERSION";

  public MtmDocumentVersionDAObject(SessionContainer sessionContainer, Connection dbConn) {
    super(sessionContainer, dbConn);
  }

  protected void initDBSetting() {
    this.baseTableName = TABLE_NAME;
    this.vecDBColumn.add("ID");
    this.vecDBColumn.add("DOCUMENT_ID");
    this.vecDBColumn.add("VERSION_ID");
    this.vecDBColumn.add("RECORD_STATUS");
    this.vecDBColumn.add("UPDATE_COUNT");
    this.vecDBColumn.add("CREATOR_ID");
    this.vecDBColumn.add("CREATE_DATE");
    this.vecDBColumn.add("UPDATER_ID");
    this.vecDBColumn.add("UPDATE_DATE");
  }

  protected synchronized AbstractBaseObject getByID(Integer id) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.DOCUMENT_ID, A.VERSION_ID, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   MTM_DOCUMENT_VERSION A ");
        sqlStat.append("WHERE  A.ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, id);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          MtmDocumentVersion tmpMtmDocumentVersion = new MtmDocumentVersion();
          tmpMtmDocumentVersion.setID(getResultSetInteger(rs, "ID"));
          tmpMtmDocumentVersion.setDocumentID(getResultSetInteger(rs, "DOCUMENT_ID"));
          tmpMtmDocumentVersion.setVersionID(getResultSetInteger(rs, "VERSION_ID"));
          tmpMtmDocumentVersion.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpMtmDocumentVersion.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpMtmDocumentVersion.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpMtmDocumentVersion.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpMtmDocumentVersion.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpMtmDocumentVersion.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpMtmDocumentVersion.setCreatorName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getCreatorID()));
          tmpMtmDocumentVersion.setUpdaterName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getUpdaterID()));
          return(tmpMtmDocumentVersion);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized List getList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.DOCUMENT_ID, A.VERSION_ID, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   MTM_DOCUMENT_VERSION A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");

        // Form the WHERE clause for filtering.
        /*
        if (searchForm.isSearchable()) {
          String searchField = searchForm.getBasicSearchField();
          if (searchField.indexOf(".") < 0) {
            searchField = "A." + searchField;
          }
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }*/
        
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 2, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 2, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          MtmDocumentVersion tmpMtmDocumentVersion = new MtmDocumentVersion();
          tmpMtmDocumentVersion.setID(getResultSetInteger(rs, "ID"));
          tmpMtmDocumentVersion.setDocumentID(getResultSetInteger(rs, "DOCUMENT_ID"));
          tmpMtmDocumentVersion.setVersionID(getResultSetInteger(rs, "VERSION_ID"));
          tmpMtmDocumentVersion.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpMtmDocumentVersion.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpMtmDocumentVersion.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpMtmDocumentVersion.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpMtmDocumentVersion.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpMtmDocumentVersion.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpMtmDocumentVersion.setCreatorName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getCreatorID()));
          tmpMtmDocumentVersion.setUpdaterName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getUpdaterID()));
          tmpMtmDocumentVersion.setRecordCount(totalNumOfRecord);
          tmpMtmDocumentVersion.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpMtmDocumentVersion);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  protected synchronized List getList() throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.DOCUMENT_ID, A.VERSION_ID, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   MTM_DOCUMENT_VERSION A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        while (rs.next()) {
          MtmDocumentVersion tmpMtmDocumentVersion = new MtmDocumentVersion();
          tmpMtmDocumentVersion.setID(getResultSetInteger(rs, "ID"));
          tmpMtmDocumentVersion.setDocumentID(getResultSetInteger(rs, "DOCUMENT_ID"));
          tmpMtmDocumentVersion.setVersionID(getResultSetInteger(rs, "VERSION_ID"));
          tmpMtmDocumentVersion.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpMtmDocumentVersion.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpMtmDocumentVersion.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpMtmDocumentVersion.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpMtmDocumentVersion.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpMtmDocumentVersion.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpMtmDocumentVersion.setCreatorName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getCreatorID()));
          tmpMtmDocumentVersion.setUpdaterName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getUpdaterID()));
          result.add(tmpMtmDocumentVersion);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected void validateInsert(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateUpdate(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateDelete(AbstractBaseObject obj) throws ApplicationException {
  }

  protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    MtmDocumentVersion tmpMtmDocumentVersion = (MtmDocumentVersion)((MtmDocumentVersion)obj).clone();

    synchronized(dbConn) {
      try {
        Integer nextID = getNextPrimaryID();
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("INSERT ");
        sqlStat.append("INTO   MTM_DOCUMENT_VERSION(ID, DOCUMENT_ID, VERSION_ID, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) ");
        sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, nextID);
        setPrepareStatement(preStat, 2, tmpMtmDocumentVersion.getDocumentID());
        setPrepareStatement(preStat, 3, tmpMtmDocumentVersion.getVersionID());
        setPrepareStatement(preStat, 4, GlobalConstant.RECORD_STATUS_ACTIVE);
        setPrepareStatement(preStat, 5, new Integer(0));
        setPrepareStatement(preStat, 6, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 7, currTime);
        setPrepareStatement(preStat, 8, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 9, currTime);
        preStat.executeUpdate();
        tmpMtmDocumentVersion.setID(nextID);
        tmpMtmDocumentVersion.setCreatorID(sessionContainer.getUserRecordID());
        tmpMtmDocumentVersion.setCreateDate(currTime);
        tmpMtmDocumentVersion.setUpdaterID(sessionContainer.getUserRecordID());
        tmpMtmDocumentVersion.setUpdateDate(currTime);
        tmpMtmDocumentVersion.setUpdateCount(new Integer(0));
        tmpMtmDocumentVersion.setCreatorName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getCreatorID()));
        tmpMtmDocumentVersion.setUpdaterName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getUpdaterID()));
        return(tmpMtmDocumentVersion);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    MtmDocumentVersion tmpMtmDocumentVersion = (MtmDocumentVersion)((MtmDocumentVersion)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE MTM_DOCUMENT_VERSION ");
        sqlStat.append("SET  DOCUMENT_ID=?, VERSION_ID=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpMtmDocumentVersion.getDocumentID());
        setPrepareStatement(preStat, 2, tmpMtmDocumentVersion.getVersionID());
        setPrepareStatement(preStat, 3, new Integer(tmpMtmDocumentVersion.getUpdateCount().intValue() + 1));
        setPrepareStatement(preStat, 4, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 5, currTime);
        setPrepareStatement(preStat, 6, tmpMtmDocumentVersion.getID());
        setPrepareStatement(preStat, 7, tmpMtmDocumentVersion.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          tmpMtmDocumentVersion.setUpdaterID(sessionContainer.getUserRecordID());
          tmpMtmDocumentVersion.setUpdateDate(currTime);
          tmpMtmDocumentVersion.setUpdateCount(new Integer(tmpMtmDocumentVersion.getUpdateCount().intValue() + 1));
          tmpMtmDocumentVersion.setCreatorName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getCreatorID()));
          tmpMtmDocumentVersion.setUpdaterName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getUpdaterID()));
          return(tmpMtmDocumentVersion);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject delete(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    MtmDocumentVersion tmpMtmDocumentVersion = (MtmDocumentVersion)((MtmDocumentVersion)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM   MTM_DOCUMENT_VERSION ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpMtmDocumentVersion.getID());
        setPrepareStatement(preStat, 2, tmpMtmDocumentVersion.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          return(tmpMtmDocumentVersion);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized void auditTrail(String opMode, AbstractBaseObject obj) throws ApplicationException {
    Vector oldValues = new Vector();
    Vector newValues = new Vector();
    MtmDocumentVersion tmpMtmDocumentVersion = (MtmDocumentVersion)this.oldValue;

    if (tmpMtmDocumentVersion != null) {
      oldValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getID()));
      oldValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getDocumentID()));
      oldValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getVersionID()));
      oldValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getRecordStatus()));
      oldValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getUpdateCount()));
      oldValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getCreatorID()));
      oldValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getCreateDate()));
      oldValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getUpdaterID()));
      oldValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getUpdateDate()));
    }

    tmpMtmDocumentVersion = (MtmDocumentVersion)obj;
    if (tmpMtmDocumentVersion != null) {
      newValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getID()));
      newValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getDocumentID()));
      newValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getVersionID()));
      newValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getRecordStatus()));
      newValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getUpdateCount()));
      newValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getCreatorID()));
      newValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getCreateDate()));
      newValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getUpdaterID()));
      newValues.add(toAuditTrailValue(tmpMtmDocumentVersion.getUpdateDate()));
    }

    auditTrailBase(opMode, oldValues, newValues);
  }

  /***********************************************************************
   * DON'T Modify the codes above unless you know what you are doing!!!  *
   * Put your own functions beblow.                                      *
   * For FINDER methods, the function name should be in the notation:    *
   *   public Object getObjectBy<Criteria>()                             *
   *   - e.g. public Object getObjectByCode()                            *
   *   public List getListBy<Criteria>()                                 *
   *   - e.g. public List getListByUserID()                              *
   * For OPERATION methods, the function name should be in the notation: *
   *   public void <Operation>ObjectBy<Criteria>()                       *
   *   - e.g. public void deleteObjectByCode()                           *
   *   public void <Operation>ListBy<Criteria>()                         *
   *   - e.g. public void deleteListByUserID()                           *
   ***********************************************************************/
  
  /**
   * Gets list of the active MtmDocumentVersion objects by document ID.
   * 
   * @param documentID the document ID
   * @return list of the active MtmDocumentVersion objects
   * @throws ApplicationException
   */
  public synchronized List getListByDocumentID(Integer documentID) throws ApplicationException {
    return getListByDocumentID(documentID, GlobalConstant.RECORD_STATUS_ACTIVE);
  }
  
  /**
   * Gets list of the MtmDocumentVersion objects by document ID and record status.
   * 
   * @param documentID the document ID
   * @param recordStatus the record status
   * @return list of the MtmDocumentVersion objects
   * @throws ApplicationException
   */
  public synchronized List getListByDocumentID(Integer documentID, String recordStatus) throws ApplicationException {
     PreparedStatement preStat = null;
     ResultSet rs = null;
     StringBuffer sqlStat = new StringBuffer();
     List result = new ArrayList();

     synchronized(dbConn) {
       try {
         sqlStat.append("SELECT A.ID, A.DOCUMENT_ID, A.VERSION_ID, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
         sqlStat.append("FROM   MTM_DOCUMENT_VERSION A ");
         sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A.DOCUMENT_ID=? ");
         preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
         this.setPrepareStatement(preStat, 1, recordStatus);
         this.setPrepareStatement(preStat, 2, documentID);
         rs = preStat.executeQuery();
         while (rs.next()) {
           MtmDocumentVersion tmpMtmDocumentVersion = new MtmDocumentVersion();
           tmpMtmDocumentVersion.setID(getResultSetInteger(rs, "ID"));
           tmpMtmDocumentVersion.setDocumentID(getResultSetInteger(rs, "DOCUMENT_ID"));
           tmpMtmDocumentVersion.setVersionID(getResultSetInteger(rs, "VERSION_ID"));
           tmpMtmDocumentVersion.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
           tmpMtmDocumentVersion.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
           tmpMtmDocumentVersion.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
           tmpMtmDocumentVersion.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
           tmpMtmDocumentVersion.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
           tmpMtmDocumentVersion.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
           tmpMtmDocumentVersion.setCreatorName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getCreatorID()));
           tmpMtmDocumentVersion.setUpdaterName(UserInfoFactory.getUserFullName(tmpMtmDocumentVersion.getUpdaterID()));
           result.add(tmpMtmDocumentVersion);
         }
         return(result);
       } catch (ApplicationException appEx) {
         throw appEx;
       } catch (SQLException sqle) {
         log.error(sqle, sqle);
         throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
       } catch (Exception e) {
         log.error(e, e);
         throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
       } finally {
         try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
         try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
       }
     }
   }

  /**
   * Delete the record of table  'MTM_DOCUMENT_VERSION' by document ID 
   * 
   * @param dmsDocumentID the document ID
   * @throws ApplicationException
   */
   public synchronized void deleteByDocID(Integer dmsDocumentID) throws ApplicationException {
     PreparedStatement preStat = null;
	     StringBuffer sqlStat = new StringBuffer();
     
	     synchronized(dbConn) {
	       try {
	       int updateCnt =0;
	       sqlStat.append("DELETE ");
	       sqlStat.append("FROM   MTM_DOCUMENT_VERSION ");
	       sqlStat.append("WHERE  DOCUMENT_ID = ?  ");
	       preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
	       setPrepareStatement(preStat, 1, dmsDocumentID);
		       updateCnt = preStat.executeUpdate();
	     	
	     }catch (SQLException sqle) {
	       log.error(sqle, sqle);
		       throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
	     } catch (Exception e) {
				       log.error(e, e);
				       throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
	     } finally {
	       try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
	     }
	    }
  }

  /**
   * Gets the corresponding abstract DmsDocument object by version ID.
   * 
   * @param versionID the dmsVersion ID
   * @return the corresponding abstract DmsDocument object
   * @throws ApplicationException
   */
  public synchronized AbstractBaseObject getDocumentByVersionID(Integer versionID) throws
    ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    synchronized (dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.DOCUMENT_NAME, A.DOCUMENT_TYPE, A.PARENT_ID, A.ROOT_ID, A.PRIORITY, A.CREATE_TYPE, A.EFFECTIVE_START_DATE, A.EFFECTIVE_END_DATE, A.REMINDER_AMOUNT, A.REMINDER_TYPE, A.NOTIFICATION_WAY,A.OWNER_ID, A.REFERENCE_NO, A.DESCRIPTION, A.ITEM_SIZE, A.ITEM_STATUS, A.CHECKOUT_ID, A.ALERT_EDIT_ID, A.ALERT_INVITE_ID, A.USER_DEF_1, A.USER_DEF_2, A.USER_DEF_3, A.USER_DEF_4, A.USER_DEF_5, A.USER_DEF_6, A.USER_DEF_7, A.USER_DEF_8, A.USER_DEF_9, A.USER_DEF_10, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM DMS_DOCUMENT A,MTM_DOCUMENT_VERSION B ");
        sqlStat.append("WHERE  A.ID = B.DOCUMENT_ID AND A.RECORD_STATUS= 'A' AND B.VERSION_ID = ?  ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, versionID);
        rs = preStat.executeQuery();
        if (rs.next()) {
          DmsDocument tmpDmsDocument = new DmsDocument();
          tmpDmsDocument.setID(getResultSetInteger(rs, "ID"));
          tmpDmsDocument.setDocumentName(getResultSetString(rs, "DOCUMENT_NAME"));
          tmpDmsDocument.setDocumentType(getResultSetString(rs, "DOCUMENT_TYPE"));
          tmpDmsDocument.setParentID(getResultSetInteger(rs, "PARENT_ID"));
          tmpDmsDocument.setRootID(getResultSetInteger(rs, "ROOT_ID"));
          tmpDmsDocument.setPriority(getResultSetString(rs, "PRIORITY"));
          tmpDmsDocument.setCreateType(getResultSetString(rs, "CREATE_TYPE"));
          tmpDmsDocument.setEffectiveStartDate(getResultSetTimestamp(rs, "EFFECTIVE_START_DATE"));
          tmpDmsDocument.setEffectiveEndDate(getResultSetTimestamp(rs, "EFFECTIVE_END_DATE"));
          tmpDmsDocument.setReminderAmount(getResultSetInteger(rs, "REMINDER_AMOUNT"));
          tmpDmsDocument.setReminderType(getResultSetString(rs, "REMINDER_TYPE"));
          tmpDmsDocument.setNotificationWay(getResultSetStringAry(rs, "NOTIFICATION_WAY", ";"));
          tmpDmsDocument.setOwnerID(getResultSetInteger(rs, "OWNER_ID"));
          tmpDmsDocument.setReferenceNo(getResultSetString(rs, "REFERENCE_NO"));
          tmpDmsDocument.setDescription(getResultSetString(rs, "DESCRIPTION"));
          tmpDmsDocument.setItemSize(getResultSetInteger(rs, "ITEM_SIZE"));
          tmpDmsDocument.setItemStatus(getResultSetString(rs, "ITEM_STATUS"));
          tmpDmsDocument.setCheckoutID(getResultSetInteger(rs, "CHECKOUT_ID"));
          tmpDmsDocument.setAlertEditID(getResultSetInteger(rs, "ALERT_EDIT_ID"));
          tmpDmsDocument.setAlertInviteID(getResultSetInteger(rs, "ALERT_INVITE_ID"));
          tmpDmsDocument.setUserDef1(getResultSetString(rs, "USER_DEF_1"));
          tmpDmsDocument.setUserDef2(getResultSetString(rs, "USER_DEF_2"));
          tmpDmsDocument.setUserDef3(getResultSetString(rs, "USER_DEF_3"));
          tmpDmsDocument.setUserDef4(getResultSetString(rs, "USER_DEF_4"));
          tmpDmsDocument.setUserDef5(getResultSetString(rs, "USER_DEF_5"));
          tmpDmsDocument.setUserDef6(getResultSetString(rs, "USER_DEF_6"));
          tmpDmsDocument.setUserDef7(getResultSetString(rs, "USER_DEF_7"));
          tmpDmsDocument.setUserDef8(getResultSetString(rs, "USER_DEF_8"));
          tmpDmsDocument.setUserDef9(getResultSetString(rs, "USER_DEF_9"));
          tmpDmsDocument.setUserDef10(getResultSetString(rs, "USER_DEF_10"));
          tmpDmsDocument.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpDmsDocument.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpDmsDocument.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpDmsDocument.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpDmsDocument.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpDmsDocument.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpDmsDocument.setCreatorName(UserInfoFactory.getUserFullName(tmpDmsDocument.getCreatorID()));
          tmpDmsDocument.setUpdaterName(UserInfoFactory.getUserFullName(tmpDmsDocument.getUpdaterID()));
          return (tmpDmsDocument);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try {
          rs.close();
        } catch (Exception ignore) {} finally {
          rs = null;
        }
        try {
          preStat.close();
        } catch (Exception ignore) {} finally {
          preStat = null;
        }
      }
    }
  }  
  
  public synchronized AbstractBaseObject insertOnly(AbstractBaseObject obj) throws ApplicationException {
    return this.insert(obj);
  }
}
